package com.broada.apm.es.indices;

import java.util.HashMap;
import java.util.Map;

import org.elasticsearch.common.settings.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.broada.apm.es.indices.service.IndexService;
import com.broada.apm.es.indices.service.impl.IndexServiceImpl;
import com.broada.apm.indicator.api.common.ApmDataIndicatorException;
import com.broada.apm.utils.ExceptionUtils;

/**
 * 
 * index管理类
 * 
 * @author louyi Create By 2014-11-21 上午10:56:20
 */
public class IndicesManager {
	private static Logger log = LoggerFactory.getLogger(IndicesManager.class);
	/* 缓存 */
	private static final Map<String, String> cache = new HashMap<String, String>();
	private static IndexService indexService = new IndexServiceImpl();
	private static IndicesManager indicesManager = new IndicesManager();

	public static IndicesManager getInstance() {
		return indicesManager;
	}

	private IndicesManager() {
		init();
	}

	/**
	 * 缓存所有索引
	 */
	private static void init() {
		try {
			String[] indexs = indexService.searchIndex("apm*");
			if(indexs != null){
				for (String index : indexs) {
					cache.put(index, index);
				}
			}
		} catch (ApmDataIndicatorException e) {
			ExceptionUtils.error(log, "索引缓存失败", e);
		}
	}

	public void buildIndex(String index, Settings settings) throws Exception {
		if (!cache.containsKey(index)) {
			cache.put(index, index);
			indexService.buildIndex(index, null, settings);
		}
	}

	public void buildIndex(String index) throws Exception {
		if (!cache.containsKey(index)) {
			cache.put(index, index);
			indexService.buildIndex(index);
		}
	}

	/**
	 * 如果cache中不存在索引，则从库里重新加载索引到cache
	 * 
	 * @param index
	 * @return
	 * @throws ApmDataIndicatorException
	 *           s
	 */
	public boolean existsIndex(String index) throws ApmDataIndicatorException {
		if (!cache.containsKey(index)) {
			if (!indexService.existsIndex(index))
				return false;
			cache.put(index, index);
		}
		return true;
	}

	public String[] searchIndex(String... index) throws ApmDataIndicatorException {
		return indexService.searchIndex(index);
	}

	public boolean deleteIndex(String... indices) throws ApmDataIndicatorException {
		return indexService.deleteIndex(indices);
	}

	public boolean deleteFromCache(String... indices) throws ApmDataIndicatorException {
		for (String indice : indices) {
			cache.remove(indice);
		}
		return true;
	}
}